<template>
  <div class="bhAnalysis-section-container">
    <div class="bar-list flex-box">
      <div class="btn-label">{{$t('product.qrcode.text.text25')}}：</div>
      <bbx-date-period 
        v-model="periodValue"
        value-format="x"
        range
        @change="handlerTimePeriodChange"
      />
    </div>

      <div class="bar-list">
        <div class="btn-label">{{$t('product.qrcode.text.text15')}}：</div>
        <el-select 
          v-model="echartParams.templateId"
          :placeholder="$t('common.placeholder.select')"
          @change="chooseSearch('templateId')"
        >
          <el-option v-if="isAll" value='' :label="$t('common.base.all')"></el-option>
          <el-option
            v-for="item in moduleOptions"
            :key="item.id"
            :label="item.productIntroduction"
            :value="item.id">
          </el-option>
        </el-select>
      </div>

      <div class="bar-list">
        <div class="btn-label">{{$t('common.base.productType')}}：</div>
        <el-select 
          v-model="echartParams.productTypeId" 
          v-loadmore="catalogLoadmore"
          :placeholder="$t('common.placeholder.select')"
          @change="chooseSearch"
        >
          <el-option v-if="isAll" value='' :label="$t('common.base.all')"></el-option>
          <el-option
            v-for="item in mProductTypeList"
            :key="item.id"
            :label="item.catalogName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>

      <div class="bar-list">
        <div class="btn-label">{{ $t('product.qrcode.text.text27') }}：</div>
        <el-radio-group v-model="echartParams.businessModule" @change="chooseSearch">
          <el-radio-button :label="radioBtnLabel">{{ $t('common.base.all') }}</el-radio-button>
          
          <template v-for="(value, name) of businessModule">
              <el-radio-button :key="name" :label="name">{{ value }}</el-radio-button>
          </template>
        </el-radio-group>
      </div>

      <div class="bar-list">
        <div class="btn-label">{{ $t('product.qrcode.text.text26') }}：</div>
        <el-radio-group v-model="echartParams.dataFormat" @change="chooseSearch">
          <el-radio-button label="NUMBER_OF_TIMES">{{isVisit ? $t('product.qrcode.text.text28') : $t('product.qrcode.text.text30')}}</el-radio-button>
          <el-radio-button label="NUMBER_OF_PEOPLE">{{isVisit ? $t('product.qrcode.text.text29') : $t('product.qrcode.text.text31')}}</el-radio-button>
        </el-radio-group>
      </div>
      <!-- 图表区域 -->
      <div class="chart-box">
        <div v-show="echartData.length" :id="echartId"></div>
        <stats-chart-empty v-show="!echartData.length">
          {{$t('common.base.tip.noData')}}
        </stats-chart-empty>
      </div>
      <!-- 表格区域 -->

      <div class="bhAnalysis-staff-category-wrap">
        <div class="bhAnalysis-table-header">
          <h3>{{ $t('product.qrcode.text.text32') }}</h3>
          <button v-if="allowExport && isWhiteList" type="button" class="btn btn-primary btn-sm" @click="exportData">{{ $t('common.base.export') }}</button>          
        </div>
        <div class="bhAnalysis-table">
          <span v-if="dateRange">{{ dateRange }}</span> 
          <el-table 
            v-table-style
            stripe 
            border 
            header-row-class-name="common-list-table-header taks-list-table-header"
            :data="tableData">
            <el-table-column fixed="left" minWidth="110" :label="$t('common.form.type.date')" prop="date"></el-table-column>
            <el-table-column minWidth="130" :label="$t('product.qrcode.type.phone')" prop="phone"></el-table-column>
            <el-table-column minWidth="130" :label="$t('product.qrcode.type.userName')" prop="userName" ></el-table-column>

            <template v-if="isVisit">
              <el-table-column minWidth="170" :label="$t('product.qrcode.type.time')" prop="time" ></el-table-column>
              <el-table-column minWidth="200" :label="$t('product.qrcode.type.business')" prop="business" ></el-table-column>
            </template>
            <template v-else>
              <el-table-column minWidth="170" :label="$t('product.qrcode.type.time2')" prop="time" ></el-table-column>
              <el-table-column minWidth="200" :label="$t('product.qrcode.type.business2')" prop="business" ></el-table-column>
            </template>

            <el-table-column minWidth="150" :label="$t('product.qrcode.type.productName')" prop="productName" ></el-table-column>
            <el-table-column minWidth="150" :label="$t('common.base.productType')" prop="productType" ></el-table-column>
            <el-table-column minWidth="150" :label="$t('product.qrcode.type.superCodeTem')" prop="superCodeTem" ></el-table-column>

          </el-table>
          <el-pagination class="bhAnalysis-footer-pagination"
                         background 
                         :page-sizes="defaultTableData.defaultPageSizes"
                         :current-page="page.pageNum"
                         @current-change="jump"
                         @size-change="handleSizeChange"
                         layout="prev, pager, next, sizes, jumper"
                         :total="total">
          </el-pagination>
        </div>
      </div>
  </div>
</template>
<script>

/* echarts */
import echarts from 'echarts';
import _ from 'lodash';
/* util */
import { formatDate, dayTimeEnd, FormatTemplate, nearDateBy } from 'pub-bbx-utils';
import { getRootWindowInitData } from '@src/util/window'
let rootWindowInitDataData = getRootWindowInitData();

// mixins
import BhAnalysisMixin from '../mixins';
// api
import * as producqQrcode from '@src/api/productQrcode';
/* components */
import BbxDatePeriod from '@src/component/Bbx/DatePeriod'
import StatsChartEmpty from '@src/modules/report/common/StatsChartEmpty.vue';
import i18n from '@src/locales';
import { defaultTableData } from '@src/util/table'

const VISIT = {
  PRODUCT_VIDEO: i18n.t('product.qrcode.type.productVideo'),
  PRODUCT_INSTRUCTION: i18n.t('product.qrcode.type.productInstruction'),
  PRODUCT_REPOSITORY: i18n.t('product.productWiki'),
  PRODUCT_RART: i18n.t('product.productPart'),
  COMPANY: i18n.t('common.base.company'),
  MALL: i18n.t('common.base.mall'),
}
const BEHAVIOR = {
  SERVICE_EVENT: i18n.t('common.base.serviceEvent'),
  PRODUCT_REG: i18n.t('common.base.productRegister'),
  ONLINE_SERVICE: i18n.t('common.base.onlineService'),
  SUBMIT_ORDER: i18n.t('product.qrcode.type.submitOrder'),
  ADD_SHOPPING_CART: i18n.t('product.qrcode.type.addShoppingCart'),
}

const sevenDays = [+nearDateBy(7, 'day'), +dayTimeEnd()]

const transFetchTimeType = (type) => {
  // 目前年月先这么写，后面有需求再改
  return type === 'date' ? 'DAY' : 'MONTH'
}

export default {
  mixins: [BhAnalysisMixin],
  components: {
    BbxDatePeriod,
    [StatsChartEmpty.name]: StatsChartEmpty
  },
  data() {
    return {
      defaultTableData,
      echartParams: {
        qrcode: '',
        startDate: '',
        endDate: '',
        businessModule: this.radioBtnLabel,
        dataType: 'DAY',
        dataFormat: 'NUMBER_OF_TIMES',
        templateId: '',
        currentType: this.currentType,
        productTypeId: ''
      },
      total: 0,
      page: { // 表格的数据
        pageNum: 1,
        pageSize: 10,
      },
      echartData: [], // 图表数据
      tableData: [], // 表格数据
      barBox: null,
      periodValue: {
        type: 'date',
        startTime: null,
        endTime: null,
      },
      initQrCodeT: 0
    }
  },
  props: {
    chartType: {
      type: String
    },
    // 当前模块
    currentType: {
      type: String,
      default: ''
    },
    // 图表id
    echartId: {
      type: String,
      default: 'visitEchart',
    },
    moduleOptions: {
      type: Array,
      default:(()=> [])
    },
    // 业务模块全部按钮的key
    radioBtnLabel: {
      type: String,
      require: true
    },
    qrCodeId: {
      type: String | Number,
      default: ''
    },
    // 是否是全部
    isAll: {
      type: Boolean,
      default: true
    },
    chartType: {
      type: String,
      default: ''
    }
  },
  watch: {
    qrCodeId: {
      handler(nl, ol){
        this.initQrCodeT = 0;
        this.echartParams.qrcode = nl;
        if(this.isAll){ // 综合
          this.echartParams.templateId = '';
          this.echartParams.productTypeId = '';
          this.mProductTypeList = [];
          this.initDatail();
          this.getRelationType();
        }else { // 单个
          this.initQrCodeT++;
        }
      },
      immediate: true
    },
    // 单个二维码行为分析默认展示对应的二维码模板
    moduleOptions: {
      async handler(nl, ol){
        if(!this.isAll && nl.length) this.echartParams.templateId = nl[0]?.id;
        const id = nl[0]?.id || '';

        if(id && !this.isAll) await this.getRelationType(id);
        this.initQrCodeT++;
      }
    },
    // 单个二维码行为分析默认展示对应的产品类型
    mProductTypeList: {
      handler(nl, ol){
        if(!this.isAll){
          this.echartParams.productTypeId = nl[0]?.id || '';
          this.initQrCodeT++;
        }
      }
    },
    // 记录行为 避免二维码模板和产品类型还取到值就请求数据
    initQrCodeT(nl, ol){
      if(nl === 3) this.initDatail();
    }
  },
  computed: {
    // 显示选择的时间区间
    dateRange(){
      const { startTime, endTime } = this.periodValue
      if(!startTime || !endTime) return '';
      return `${formatDate(startTime, FormatTemplate.date)} ~ ${formatDate(endTime, FormatTemplate.date)}`
    },
    // 是否是访问分析
    isVisit(){
      return this.currentType === 'visit';
    },
    // 访问分析 or 行为分析 的业务模板
    businessModule(){
      return this.isVisit ? VISIT : BEHAVIOR;
    },
    // 企微导出权限
    isWhiteList() {
      const { tenantType, WHITE_LIST } = rootWindowInitDataData;
      if (tenantType == 2) {
        return WHITE_LIST;
      }
      return true;
    },
    auth() {
      return rootWindowInitDataData?.user?.auth || rootWindowInitDataData?.loginUser?.authorities;
    },
    // 导出权限
    allowExport() {
      return this.auth?.REPORT_EXPORT;
    },
  },
  mounted() {
    this.initDate();

    // 初始化图表
    this.barBox = echarts.init(document.getElementById(this.echartId));
    this.$nextTick(()=>{
      window.addEventListener('resize', _.debounce(()=>{
        this.barBox.resize();
      }))
    })
    if(this.isAll) this.initDatail();
  },
  methods: {
    // 初始化数据
    initDatail(){
      const { startTime, endTime } = this.periodValue;
      if(!startTime || !endTime) return;

      this.page.pageNum = 1;
      this.getEchartData()
      this.getTableList()
    },
    // 图表的数据
    async getEchartData() {
      try{
        const { startTime, endTime, type } = this.periodValue;
        const params = {
          ...this.echartParams,
          ...this.page,
          startDate: startTime,
          endDate: endTime,
          type: transFetchTimeType(type),
        }
        let {data, code, msg} = await producqQrcode.getQrcodeChartData(params);
        this.loading = false;
        if(code !== 200) return this.$message.error(msg);

        this.echartData = data.points;
        this.$nextTick(()=>{
          this.initEchart();
        })
      }catch(e){
        console.log('producqQrcode.getQrcodeChartData', e);
      }
    },
    // 获取表格数据
    async getTableList() {
      try {
        const { startTime, endTime, type } = this.periodValue
        const params = {
          ...this.echartParams,
          ...this.page,
          startDate: startTime,
          endDate: endTime,
          type: transFetchTimeType(type),
        }
        let {data, code, msg} = await producqQrcode.getQrcodeChartDetail(params);
          this.loading = false;
          if(code !== 200) return;
          
          const { total, records } = data?.page;
          this.total = total || 0;
          this.tableData = records || [];
      }catch(e){
        console.log('producqQrcode.getQrcodeChartDetail', e);
      }
    },
    chooseSearch(type) {
      if(type === 'templateId'){
        this.echartParams.productTypeId = '';
        this.getRelationType(this.echartParams.templateId);
      }

      this.initDatail();
    },

    async initEchart() {
      let xAxisData = []
      let seriesData = []

      this.echartData.forEach((item) => {
         xAxisData.push(item.date);
         seriesData.push(item.num)
      })
      let typeValue = ''
      const isPersonCount = this.echartParams.dataFormat == 'NUMBER_OF_PEOPLE'
      if(this.isVisit) {
        typeValue = isPersonCount ? this.$t('product.qrcode.text.text29') : this.$t('product.qrcode.text.text28')
      }else {
        typeValue = isPersonCount ? this.$t('product.qrcode.text.text31') : this.$t('product.qrcode.text.text30')
      }
      // 指定图表的配置项和数据
      var option = {
        color: '#5B8FF9',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        dataZoom: [
          {
            type: 'inside'
          },
          {
            type: 'slider'
          }
        ],
        xAxis: [
            {
              type: 'category',
              data: xAxisData,
              axisPointer: {
                  type: 'shadow'
              }
            }
        ],
        toolbox: {
          show: true,
          right: 20,
          feature: {
            magicType: { type: ['line', 'bar'] },
            // restore: {}, // 还原
            // saveAsImage: {}
          }
        },
        yAxis: [
          {
            type: 'value',
            name:  this.echartParams.dataFormat == 'NUMBER_OF_PEOPLE' ? this.$t('product.qrcode.text.text33') : this.$t('product.qrcode.text.text34'),
          }
        ],
        series: [
          {
            barMaxWidth: '40%',
            name: typeValue,
            type: 'bar',
            data: seriesData,
            label: {
              show: true,
              position: '',
              color: '#fff',
            }
          },
        ]
      };
      this.barBox.clear();
      this.barBox.setOption(option);
      this.$nextTick(() => {
        this.barBox.resize()
      })
    },
    // 导出数据
    exportData() {
      if(this.total > 10000) return this.$message({
        message: this.$t('product.qrcode.tips.tip12', {count: 10000}),
        type: 'error',
      })

      producqQrcode.exportQrcodeChartDetail({
        ...this.echartParams,
        pageNum: 0,
        pageSize: 0
      }).then(res => {
        if(res.code !== 200) {
          return this.$message({
            message: res.msg,
            duration: 1500,
            type: 'error',
          })
        }
        window.parent.showExportList()
        window.parent.exportPopoverToggle(true)
      }).catch(error => {
        console.log('exportQrcodeChartDetail', error)
      })

      this.exportTrack(false)
    },

    exportTrack(isExportAll) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType
      }, '*')
    },

    jump(currentPage){
      this.page.pageNum = currentPage
      this.getTableList();
    },
    handleSizeChange(pageSize) {
      this.page.pageNum = 1;
      this.page.pageSize = pageSize;
      this.getTableList();
    },
    // 日期选择切换
    handlerTimePeriodChange(e){
      // 埋点
      if(!e.startTime || !e.endTime) return;
      this.initDatail();
      this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    },
    // [开始时间, 结束时间]  为日时 周期为近七天
    initDate(){
      this.periodValue = {  
        type: 'date',
        startTime: sevenDays[0],
        endTime: sevenDays[1],
      }
    },
    // 重置
    reset(info = {}){
      this.initDate();
      this.echartParams.templateId = '';
      this.echartParams.productTypeId = '';
      this.echartParams.dataFormat = 'NUMBER_OF_TIMES';
      this.echartParams.businessModule = info.businessModule;
      this.initDatail();
    }
  }
}
</script>
<style lang="scss">

  .bhAnalysis-section-container {
    margin: 24px 16px 16px 16px;
    .bhAnalysis-staff-category-wrap {
      margin-top:20px;
      .bhAnalysis-table-header {
        display: flex;
        justify-content: space-between;
        margin-bottom:10px;
      }
      .bhAnalysis-table {
        >span {
          display: block;
          margin-bottom: 14px;
        }
      }
      .bhAnalysis-footer-pagination {
        margin-top:10px;
        text-align: right;
      }
    }
    
    .bar-list {
       margin-bottom: 4px;

      .btn-label {
        width: 120px;
        height: 32px;
        font-size: 14px;
        display: inline-block;
        text-align: right;
        color: #262626;
      }
      .btn-item {
        display: inline-block;
        margin-right: 10px;
      }
    }

    .flex-box {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .btn-label {
        line-height: 29px;
      }
    }

    .chart-box {
      position: relative;
      height: 520px;
      
      >div {
        height: 100%;
      }
    }
  }
</style>
<style lang="scss" scoped>
  ::v-deep .el-date-editor .el-input__suffix .el-input__icon {
    opacity: 0;
}
</style>